<template>
<!-- 首页 -->
  <div class="home-container">
    <!-- 顶部数据概览 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="6" v-for="(card, index) in summaryCards" :key="index">
        <el-card shadow="hover" class="stat-card">
          <div class="flex items-center">
            <div class="icon-box" :style="{backgroundColor: card.color}">
              <!-- 修正为 card.icon -->
              <el-icon :size="24" :color="card.iconColor"><component :is="card.icon" /></el-icon>
            </div>
            <div class="ml-3">
              <div class="text-sm text-gray-500">{{ card.title }}</div>
              <div class="text-2xl font-bold">{{ card.value }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 中部核心图表区 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="16">
        <el-card shadow="hover">
          <template #header>
            <div class="flex justify-between items-center">
              <span>业务数据趋势</span>
              <el-radio-group v-model="chartType" size="small">
                <el-radio-button label="line">折线图</el-radio-button>
                <el-radio-button label="bar">柱状图</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div style="height: 300px">
            <v-chart :option="chartOption" autoresize />
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <span>快捷操作</span>
          </template>
          <div class="quick-actions">
            <el-button
              v-for="action in quickActions"
              :key="action.path"
              :icon="action.icon"
              @click="router.push(action.path)"
              class="action-btn"
            >
              {{ action.name }}
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 底部表格数据 -->
    <el-card shadow="hover">
      <template #header>
        <div class="flex justify-between items-center">
          <span>最近操作记录</span>
          <el-button type="primary" link @click="refreshData">刷新数据</el-button>
        </div>
      </template>
      <el-table :data="recentActivities" style="width: 100%">
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="module" label="模块" width="120" />
        <el-table-column prop="operation" label="操作内容" />
        <el-table-column prop="status" label="状态" width="80" />
        <el-table-column prop="formattedOperationTime" label="操作时间" width="180" />
      </el-table>
      <div class="mt-4 flex justify-end">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="5"
          layout="prev, pager, next"
          :total="totalLogs"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import {
  User,
  Notebook,
  Money,
  Histogram,
  Edit,
  Upload,
  Download,
  Setting
} from '@element-plus/icons-vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import request from '@/utils/request'

use([
  CanvasRenderer,
  LineChart,
  BarChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
])

const router = useRouter()

// 数据卡片配置
const summaryCards = ref([
  { title: '注册用户', value: '', icon: User, color: '#e6f7ff', iconColor: '#1890ff' },
  { title: '慢病档案', value: '', icon: Notebook, color: '#fff7e6', iconColor: '#fa8c16' },
  { title: '报销金额', value: '', icon: Money, color: '#f6ffed', iconColor: '#52c41a' },
  { title: '医疗机构', value: '', icon: Histogram, color: '#f9f0ff', iconColor: '#722ed1' }
])

// 快捷操作按钮
const quickActions = ref([
  { name: '新建档案', icon: Edit, path: '/home/farmer-management/add' },
  { name: '数据导入', icon: Upload, path: '/data/import' },
  { name: '报表导出', icon: Download, path: '/report/export' },
  { name: '系统设置', icon: Setting, path: '/system/settings' }
])

// 图表配置
const chartType = ref('line')
const chartOption = ref({
  tooltip: { trigger: 'axis' },
  legend: { data: ['新增用户', '报销申请'] },
  xAxis: {
    type: 'category',
    data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
  },
  yAxis: { type: 'value' },
  series: [
    {
      name: '新增用户',
      type: 'line',
      data: [210, 112, 111, 214, 210, 310, 310, 310, 190, 130, 110, 190],
      smooth: true
    },
    {
      name: '报销申请',
      type: 'line',
      data: [110, 122, 111, 114, 110, 210, 220, 230, 190, 220, 210, 130], // 初始为空，等待后端数据
      smooth: true
    }
  ]
})

// 监听 chartType 的变化
watch(chartType, (newType) => {
  chartOption.value.series.forEach((series) => {
    series.type = newType
  })
})

// 操作记录表格
const currentPage = ref(1)
const statusMap = {
  '成功': 'success',
  '处理中': 'warning',
  '失败': 'danger'
}
const recentActivities = ref([])
const totalLogs = ref(0)

const refreshData = () => {
  // 这里添加数据刷新逻辑
  console.log('刷新数据...')
  fetchRecentLogs()
}

const fetchRecentLogs = async () => {
  try {
    const response = await request.get('/home/recentLogs')
    const logs = response.data || []
    recentActivities.value = logs.slice(0, 5)
    totalLogs.value = logs.length
  } catch (error) {
    console.error('获取最近操作日志失败:', error)
  }
}

onMounted(async () => {
  try {
    const userCountRes = await request.get('/home/userCount')
    summaryCards.value[0].value = userCountRes.data
    const policyCountRes = await request.get('/home/policyCount')
    summaryCards.value[1].value = policyCountRes.data
    const totalReimbursementAmountRes = await request.get('/home/totalReimbursementAmount')
    summaryCards.value[2].value = `¥${totalReimbursementAmountRes.data}`
    const medicalInstitutionCountRes = await request.get('/home/medicalInstitutionCount')
    summaryCards.value[3].value = medicalInstitutionCountRes.data

    const newUsersDataRes = await request.get('/home/getRegisterTimes')
    console.log('接口返回的每月注册用户数量数据:', newUsersDataRes.data);
    // 确保 newUsersDataRes.data 是一个数组
    const newUsersDataArray = Array.isArray(newUsersDataRes.data) ? newUsersDataRes.data : [];
    console.log('处理后用于图表的新增用户数据:', newUsersDataArray);
    chartOption.value.series[0].data = newUsersDataArray;
    console.log('更新后的新增用户图表配置:', chartOption.value);

    // 获取报销申请数据
    const reimbursementDataRes = await request.get('/home/getMonthlyCount')
    console.log('接口返回的每月报销申请数量数据:', reimbursementDataRes.data);
    // 确保 reimbursementDataRes.data 是一个数组
    const reimbursementDataArray = Array.isArray(reimbursementDataRes.data) ? reimbursementDataRes.data : [];
    console.log('处理后用于图表的报销申请数据:', reimbursementDataArray);
    chartOption.value.series[1].data = reimbursementDataArray;
    console.log('更新后的报销申请图表配置:', chartOption.value);

    fetchRecentLogs()
  } catch (error) {
    console.error('获取数据失败:', error)
  }
})
</script>

<style scoped>
.home-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.stat-card {
  border-radius: 8px;
  transition: transform 0.3s;
}
.stat-card:hover {
  transform: translateY(-5px);
}

.icon-box {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.quick-actions {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  padding: 10px;
}

.action-btn {
  width: 100%;
  height: 80px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 14px;
}
.action-btn i {
  font-size: 24px;
  margin-bottom: 8px;
}

/* 响应式适配 */
@media (max-width: 1200px) {
 .quick-actions {
    grid-template-columns: 1fr;
  }
}
</style>